package com.hello.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.sql.DataSource;

import com.hello.domain.User;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.access.prepost.PreAuthorize;

public class SdaoImpl implements Sdao {
	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource ds) {
		this.jdbcTemplate = new JdbcTemplate(ds);
	}
	
	@Override
	@PreAuthorize("hasRole('ROLE_SUPERVISOR')")
	public int insert(User user) {
		// TODO Auto-generated method stub
		String sql = "INSERT INTO user(name,city,password) VALUES(?,?,?)";
		Object[] objs = new Object[] { user.getName(), user.getCity(), user.getPassword()};
		int[] ints = new int[] { Types.VARCHAR, Types.TINYINT, Types.VARCHAR};
		return this.jdbcTemplate.update(sql, objs, ints);
	}

	@Override
	public User findUserByName(String name) {
		// TODO Auto-generated method stub
		String sql = "SELECT name,password FROM user WHERE name = ?";
		return this.jdbcTemplate.queryForObject(sql, new Object[] { name }, new int[] { Types.VARCHAR }, new RowMapper<User>() {

			@Override
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				// TODO Auto-generated method stub
				User user = new User();
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				return user;
			}});
	}

	@Override
	public List findAllUsers() {
		// TODO Auto-generated method stub
		String sql = "SELECT name,password FROM user";
		return this.jdbcTemplate.queryForList(sql);
	}

}
